<script lang="ts" setup>
import { onMounted, ref, watch, reactive, markRaw, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { SearchApi } from '@/apis/index'

import type { SearchHotWordList, SuggestTag, ResultType, MediaBangumi, BiliUser, MediaFt, TypeChoice } from '@/TypingMore/SearchTyping'

import SearchVideo from '@/components/searchComponents/SearchVideo.vue'
import FancyOpera from '@/components/searchComponents/FancyOpera.vue'
import MoviesAndAv from '@/components/searchComponents/MoviesAndAv.vue'
import UpUser from '@/components/searchComponents/UpUser.vue'
import ItIsTheEnd from '@/components/ItIsTheEnd.vue'

type tabType = {
    name: string,
    tabComp: any
}

type Comp = Pick<tabType, 'tabComp'>

const tabData = reactive<tabType[]>([
    {
        name: '综合',
        tabComp: markRaw(SearchVideo)
    },
    {
        name: '番剧',
        tabComp: markRaw(FancyOpera)
    },
    {
        name: '影视',
        tabComp: markRaw(MoviesAndAv)
    },
    {
        name: 'up主',
        tabComp: markRaw(UpUser)
    },
])

let currentTab = reactive<Comp>({
    tabComp: tabData[0].tabComp
})

const switchTab = (tab: tabType) => {
    currentTab.tabComp = tab.tabComp
}

const router = useRouter()

const route = useRoute()

const value = ref('')

const typeChoice = ref<TypeChoice[]>([
    {
        title: '默认排序',
        type: ''
    },
    {
        title: '播放多',
        type: 'click'
    },
    {
        title: '新发布',
        type: 'pubdate'
    },
    {
        title: '弹幕多',
        type: 'dm'
    }
])

const search_type = ref('综合')

const hotWord = ref<SearchHotWordList[]>([])

const mediaBangumiData = ref<MediaBangumi[]>([])

const biliUser = ref<BiliUser[]>([])

const mediaFt = ref<MediaFt[]>([])

const choice = ref('')

const suggestResult = ref<SuggestTag[]>([])

const localSearch = ref<Array<string>>([])

const searchResult = ref<ResultType[]>([{
    result_type: '',
    data: []
}])
const setTypeChoice = (val: string) => {
    choice.value = val
}
// 热门搜索关键字
const getHotword = async () => {

    let { data } = await SearchApi.getHotwordData()
    hotWord.value = data.list.filter((item, index) => {
        return index < 4
    })
    console.log('**** Hotword ***', data, hotWord.value, '**** Hotword ****')

}
//联想数据
const getSuggestResult = async () => {
    if (value.value) {
        let { data } = await SearchApi.getSuggest(value.value)
        suggestResult.value = data.result.tag
        console.log('\n**** suggestResult ***', data, suggestResult.value, '\n**** suggestResult ****')
    } else {
        showResult('')
    }
}
// 获取cookie携带参数
const getSpiData = async () => {
    let { data } = await SearchApi.getSpi() as any
    console.log(data)
    Setcookie('buvid3', data.data.b_3)
}
// 搜索后做历史记录
const showResult = async (keword: string) => {
    router.replace({
        name: 'search',
        query: {
            keword
        }
    })
    if (keword) {
        localSearch.value = [...localSearch.value, keword]
        let arr = localStorage.getItem('bilibiliSearchLocal') as string
        let count = 0
        if (!localStorage.getItem('bilibiliSearchLocal')) {
            localStorage.setItem('bilibiliSearchLocal', JSON.stringify(localSearch.value))
        } else {
            for (let i = 0; i < JSON.parse(arr).length; i++) {
                if (JSON.parse(arr)[i] !== keword) {
                    count++
                }
            }
            console.log(count, JSON.parse(arr).length)
            if (count === JSON.parse(arr).length) {
                localStorage.setItem('bilibiliSearchLocal', JSON.stringify(localSearch.value))
            }
        }

    }

    value.value = keword
}
// 搜索到的数据
const showTypeVideo = async (keword: string) => {
    if (choice.value === '') {
        let { data } = await SearchApi.getSearchResult(keword)
        searchResult.value = [...data.data.result]
        console.log('SearchResult', data.data.result, searchResult.value)
    } else {
        let { data } = await SearchApi.getOtherChoiesData(choice.value, keword)
        searchResult.value = [{
            data: data.data.result,
            result_type: 'video'
        }]
        console.log('SearchResult', data, searchResult.value)
    }


}
// 将cookie存入
function Setcookie(name: string, value: string) {
    //设置名称为name,值为value的Cookie
    let expdate = new Date();   //初始化时间
    expdate.setTime(expdate.getTime() + 30 * 60 * 1000);   //时间单位毫秒
    document.cookie = name + "=" + value + ";expires=" + ";path=/";

    //即document.cookie= name+"="+value+";path=/";  时间默认为当前会话可以不要，但路径要填写，因为JS的默认路径是当前页，如果不填，此cookie只在当前页面生效！
}
// 返回
const goBack = () => {
    router.push('/')
}
// 清空历史搜索
const removeLoca = () => {
    localStorage.removeItem('bilibiliSearchLocal')
    localSearch.value = []
}

const searchType = computed<string>((): string => {
    if (search_type.value === '综合') {
        return 'video'
    } else if (search_type.value === '番剧') {
        return 'media_bangumi'
    } else if (search_type.value === 'up主') {
        return 'bili_user'
    } else {
        return 'media_ft'
    }
})
getSpiData()
getHotword()

watch(search_type, () => {
    if (route.query.keword) {
        let keword = route.query.keword as string
        SearchApi.getOtherData(keword, searchType.value).then(({ data }) => {
            if (data.data.result) {
                if (searchType.value === 'media_bangumi') {
                    mediaBangumiData.value = data.data.result
                } else if (searchType.value === 'bili_user') {
                    biliUser.value = data.data.result
                } else if (searchType.value === 'media_ft') {
                    mediaFt.value = data.data.result
                    console.log(mediaFt.value)
                }
            }
            console.log(data)
        })
    }
})

watch(choice, () => {
    if (route.query.keword) {
        let keword = route.query.keword as string
        showTypeVideo(keword)
    }
})

onMounted(() => {
    if (localStorage.getItem('bilibiliSearchLocal')) {
        let arr = localStorage.getItem('bilibiliSearchLocal') as string
        localSearch.value = JSON.parse(arr)
    }

    if (route.query.keword) {
        let keword = route.query.keword as string
        value.value = keword
        showTypeVideo(keword)
    }
})

</script>

<template>
    <div class="" style="background-color: #f4f4f4; width: 100vw; height: 100vh;">
        <div class=" flex items-center bg-white pr-3">
            <van-search v-model="value" @update:model-value="getSuggestResult" @search="showResult(value)"
                placeholder="请输入搜索关键词" class=" flex-1" />
            <span @click="goBack" class=" bg-white" style="color: #fb7299;">取消</span>
        </div>
        <div class=" flex justify-between items-center px-5 h-11 bg-white" v-show="route.query.keword">
            <div v-for="t in tabData" :key="t.name" @click="search_type = t.name, switchTab(t)"
                :class="{ 'active-bottom': search_type === t.name }">{{ t.name }}</div>
        </div>
        <div v-show="!route.query.keword">
            <div v-show="!value">
                <div class=" bg-white">
                    <div class=" pl-3 text-sm text-gray-400">大家都在搜</div>
                    <div class="flex flex-wrap px-3 pb-3 text-sm">
                        <div class=" border px-3 mt-3 mr-3 py-2 rounded-full" v-for="h in hotWord" :key="h.id"
                            @click="showResult(h.keyword)">
                            <p>{{ h.keyword }}</p>
                        </div>
                    </div>
                </div>
                <div class=" bg-white">
                    <div class=" pl-3  text-sm text-gray-400">
                        历史搜索
                    </div>
                    <div>
                        <div class="border-b py-3 pl-3" v-for="l in localSearch" :key="l" @click="showResult(l)"><span
                                class="iconfont icon-lishijilu mr-1 text-gray-400"></span>{{ l }}</div>
                    </div>
                    <div class=" py-3 pl-3 text-center " @click="removeLoca">清楚历史记录</div>
                </div>
            </div>
        </div>
        <div class=" bg-white" v-show="value">
            <div v-for="(s, index) in suggestResult" :key="s.value + index" @click="showResult(s.value)">
                <p class="border-b py-3 pl-3">{{ s.value }}</p>
            </div>
        </div>

        <div v-show="route.query.keword">
            <component :is="currentTab.tabComp" :searchResult="searchResult" :biliUser="biliUser"
                :mediaBangumiData="mediaBangumiData" :mediaFt="mediaFt" :choice="choice" :typeChoice="typeChoice"
                @setTypeChoice="setTypeChoice"></component>
            <!-- <SearchVideo :searchResult="searchResult" v-show="search_type === 'video'" /> -->
        </div>
        <ItIsTheEnd></ItIsTheEnd>
    </div>
</template>

<style>
.keyword {
    color: #f69;
    font-style: normal;
}

.img-rounde {
    border-radius: 3px;
}

.line-two {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.active-bottom {
    color: #f69;
    border-bottom: 1px solid #f69;
}
</style>